package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.domain.TbProd;
import com.bwie.es.EsProd;
import com.bwie.mapper.TbProdMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/11/21 10:40
 */

@Component
public class SyncProdTask {

    @Autowired
    ElasticsearchRestTemplate esTemplate;

    @Autowired
    TbProdMapper tbProdMapper;

    /**
     * 同步库中的商品到ES中
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncProd(){
        System.out.println("开始同步商品到ES中...");

        //--1 判断ES索引是否存在，如果不存在，创建索引
        IndexOperations indexOps = esTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists) {
            // 索引不存，创建索引
            indexOps.create();

            // 创建静态映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }

        //--2 获取商品列表，循环遍历，调用ES的API，添加商品到ES中
        List<TbProd> tbProds = tbProdMapper.selectList(null);
        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            esTemplate.save(esProd);
        }

        System.out.println("同步商品到ES中完成...");
    }

}
